const app = getApp();
const api = require('../../../../ws_micro_shop/utils/api.js');
const { throttle, handleReplaceComma } = require('../../../common/utils/util');

Page({
  data: {
    showMask: false,
    singleDistributionList: [], // 单一分配列表
    uniformDistributionList: [], // 统一分配列表
    storeInfo: {},
    singleDisabled: true, // 单一分配按钮
    uniformDisabled: true, // 统一分配按钮
    sales: 0,
    members: 0,
    isSelectAll: false,
    uniformTargetMoney: '',
    uniformTargetUsers: '',
    selectedNumber: 0,
    ipX: false,
  },

  onShow() {
    const { date = '', store_type = '' } = this.options;
    let corpid = wx.getStorageSync('corpid');

    this.setData(
      {
        date,
        store_type,
        is_guide: app.ws_micro_shop_globalData.role,
        ipX: wx.systemInfo && wx.systemInfo.model.search('iPhone X') !== -1,
        isSaas: app.ws_micro_shop_globalData.isSaas,
        corpid
      },
      () => {
        this.getInfo();
      },
    );
  },

  getInfo() {
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });

    const { date } = this.data;
    app.ws_micro_shoprequest({
      url: api.staff.submit_preview,
      data: {
        type: 1,
        date,
      },
      success: res => {
        if (res && res.code === 0) {
          const { shop_goals: storeInfo = {}, list: singleDistributionList = [] } = res.data;
          const uniformDistributionList = singleDistributionList[0] && singleDistributionList[0].list;
          uniformDistributionList.map(item => (item.checked = false));

          this.setData(
            {
              storeInfo,
              singleDistributionList,
              uniformDistributionList,
            },
            () => {
              this.checkButtonStatus();
              this.handleCalculateTotal();
            },
          );
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  handleSingleSetting(e) {
    // 单一设置
    const { singleDistributionList } = this.data;
    const { distributiontype = '', inputtype = '', id = '' } = e.currentTarget.dataset;

    singleDistributionList[0].list.map(item => {
      if (String(item.id) === String(id)) {
        item[inputtype] = e.detail.value;
      }
    });

    this.setData(
      {
        singleDistributionList,
      },
      () => {
        this.checkButtonStatus(distributiontype);
        this.handleCalculateTotal();
      },
    );
  },

  onSingleDistribution:throttle(function() {
    // 单一分配 (这里的逻辑需要兼容之前的写法，待修改)
    const {
      is_guide = '',
      date = '',
      store_type = '',
      sales: totalPrice = 0,
      members: totalNum = 0,
      singleDistributionList,
      uniformDistributionList,
    } = this.data;
    let arr = singleDistributionList[0].list;
    let promptText = '';
    let selectedArr = [];

    arr.map(item => {
      item.target_money = handleReplaceComma(item.target_money);
      item.target_users = handleReplaceComma(item.target_users);
    })

    for (let index = 0; index < arr.length; index++) {
      if(String( arr[index].target_money) === '0' || String( arr[index].target_users) === '0') {
        promptText = '目标设置需>0';
      }else{
        if( arr[index].target_money &&  arr[index].target_users) {
          selectedArr.push(arr[index]);
          continue;
        }
        if( arr[index].target_money ||  arr[index].target_users) {
          promptText = '被分配的导购需同时设置销售业绩目标和新增会员目标';
        }
      }
    }

    if(promptText) {
      wx.showModal({
        title: '系统提示',
        content: promptText,
        showCancel: false,
      });
      return;
    }
    
    app.infomation = {
      date,
      info: JSON.stringify(arr),
    };

    app.util.navigateTo(
      '/ws_micro_shop_guide/pages/achieve-total-detail/index',
      {
        store_type,
        date,
        sum: uniformDistributionList.length,
        num: selectedArr.length,
        totalPrice,
        totalNum,
      },
      false,
    );
  },1000),

  handleUniformSetting(e) {
    // 统一设置
    const { distributiontype = '', inputtype = '' } = e.currentTarget.dataset;

    this.setData(
      {
        [inputtype]: e.detail.value,
      },
      () => {
        this.checkButtonStatus(distributiontype);
      },
    );
  },

  onUniformDistribution: throttle(function() {
    // 统一分配 (这里的逻辑需要兼容之前的写法，待修改)
    let {
      is_guide = '',
      date = '',
      store_type = '',
      singleDistributionList,
      uniformDistributionList,
      uniformTargetMoney,
      uniformTargetUsers,
      selectedNumber,
    } = this.data;
    const selectedList = [];
    let promptText = '';

    uniformTargetMoney = handleReplaceComma(uniformTargetMoney);
    uniformTargetUsers = handleReplaceComma(uniformTargetUsers);

    uniformDistributionList
      .filter(item => item.checked)
      .map(uniformItem => {
        singleDistributionList[0] &&
          singleDistributionList[0].list.map(singleItem => {
            if (singleItem.id === uniformItem.id) {
              singleItem.target_money = uniformTargetMoney;
              singleItem.target_users = uniformTargetUsers;
              selectedList.push(singleItem);
            }
          });
      });

    selectedList.map(item => {
      if(String( item.target_money) === '0' || String( item.target_users) === '0') {
        promptText = '目标设置需>0';
      }
    });

    if(promptText) {
      wx.showModal({
        title: '系统提示',
        content: promptText,
        showCancel: false,
      });
      return;
    }

    app.infomation = {
      date,
      info: JSON.stringify(selectedList),
    };

    const totalPrice = uniformTargetMoney * selectedNumber;
    const totalNum = uniformTargetUsers * selectedNumber;

    app.util.navigateTo(
      '/ws_micro_shop_guide/pages/achieve-total-detail/index',
      {
        is_guide,
        store_type,
        date,
        sum: uniformDistributionList.length,
        num: selectedNumber,
        totalPrice,
        totalNum,
      },
      false,
    );

      this.togglesMask();
  },1000),

  handleCalculateTotal() {
    // 计算单一设置下的合计
    const { singleDistributionList } = this.data;
    let sales = 0;
    let members = 0;

    singleDistributionList[0].list.map(item => {
      sales += handleReplaceComma(item.target_money,false);
      members += handleReplaceComma(item.target_users,false);
    });

    this.setData({
      sales,
      members,
    });
  },

  checkButtonStatus(distributiontype = 'single') {
    if (distributiontype === 'single') {
      const { singleDistributionList } = this.data;
      const notSelectedArr = [];
      singleDistributionList[0].list.map(item => {
        if (item.target_money && item.target_users) {
          notSelectedArr.push(item);
        }
      });
      const singleDisabled = notSelectedArr.length ? false : true;

      this.setData({
        singleDisabled,
      });
    } else {
      const { uniformDistributionList, uniformTargetMoney, uniformTargetUsers } = this.data;
      const hasSelected = uniformDistributionList.find(item => item.checked === true);
      const uniformDisabled = hasSelected && uniformTargetMoney && uniformTargetUsers;
      this.setData({
        uniformDisabled: !uniformDisabled,
      });
    }
  },

  onClearAll() {
    const { singleDistributionList } = this.data;
    singleDistributionList[0].list.map(item => {
      item.target_money = '';
      item.target_users = '';
    });

    this.setData(
      {
        singleDistributionList,
      },
      () => {
        this.handleCalculateTotal();
        this.checkButtonStatus();
      },
    );
  },

  handleClearUniform() {
    const { uniformDistributionList } = this.data;

    uniformDistributionList.map(item => (item.checked = false));

    this.setData({
      uniformDistributionList,
      uniformTargetMoney: '',
      uniformTargetUsers: '',
      selectedNumber: 0,
      isSelectAll: false,
    });
  },

  togglesMask() {
    const { showMask } = this.data;

    if (!showMask) {
      this.handleClearUniform();
    }

    this.setData({
      showMask: !showMask,
    });
  },

  handleSelect(e) {
    const { uniformDistributionList } = this.data;
    const { id = '' } = e.currentTarget.dataset;
    uniformDistributionList.map(item => {
      if (String(item.id) === String(id)) {
        item.checked = !item.checked;
      }
    });

    this.setData(
      {
        uniformDistributionList,
      },
      () => {
        this.checkSelectStatus();
        this.checkButtonStatus('uniform');
      },
    );
  },

  handleSelectAll() {
    const { uniformDistributionList, isSelectAll } = this.data;
    uniformDistributionList.map(item => (item.checked = !isSelectAll));

    this.setData(
      {
        uniformDistributionList,
        isSelectAll: !isSelectAll,
      },
      () => {
        this.checkSelectStatus();
        this.checkButtonStatus('uniform');
      },
    );
  },

  checkSelectStatus() {
    const { uniformDistributionList } = this.data;
    const isSelectAll = !uniformDistributionList.find(item => item.checked === false);
    const selectedNumber = uniformDistributionList.filter(item => item.checked).length;

    this.setData({
      isSelectAll,
      selectedNumber,
    });
  },
});
